# -*- coding: utf-8 -*-
import cgi
import datetime
import wsgiref.handlers

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
import views.TI as tiv
import models.trackingInfo as tim
import models.shippingOrder as som
import models.milestonePlan as MPm
import models.user as um
import models.status as sm
import models.city as cm
import models.option as om
from models.enhancedModel import EnhancedModel as EM

import decorator as dc
import helpers.maps as maps
import helpers.mail as mailHelper
class MPCheckerContr( webapp.RequestHandler ):

    #@dc.decorate
    def get(self, action, *params):
        if self.checkDelays() == True :
          self.response.out.write("checked!")
        else:
          self.response.out.write("not checked!")

    @staticmethod
    def checkDelays():
        mindelay = int(EM.queryLatest(om.OptionModel).filter('name =', "minimumDelay").get().value)
        query = EM.queryLatest(som.SOModel).filter('finished =', False).filter('alreadyChecked =', False)
        for (i, order) in enumerate(query):
          sendMail = False
          mp = EM.queryLatest(MPm.MPModel, order.mp).get()
          for tuple in mp.plan:
            decoded = MPm.MPModel.tupleDecode(tuple)
            expectedTime, checkpoint, expectedStatus = decoded
            now = datetime.datetime.now()
            if now>expectedTime+datetime.timedelta(minutes = mindelay):
                query = EM.queryLatest(tim.TIModel).filter('shippingOrder =', order.ident).order('time').fetch(1000) 
                matchingTI = False
                for ti in enumerate(query):
                  if (sm.StatusModel.show(ti.status)==expectedStatus) and (cm.CityModel.nearestCityCode(ti.position)==checkpoint):
                    
                    matchingTI = True
                    break
                if matchingTI==False:
                  delay = (now-expectedTime).seconds // 3600
                  if delay> mp.currentDelay:
                    mp.currentDelay = delay
                    mp.put()
                    sendMail = True
                    order.alreadyChecked= True
                    order.put()            
            else:
              break
          if sendMail==True:
            mailHelper.sendOrderReport(order)
        return True